<template>
  <el-dialog title="插入分图" :visible.sync="dialogVisible" :before-close="handleClose">
    <el-row>
      <el-col class="card" :span="12" v-for="(item, index) of figures" :key="index">
        <input
          v-if="!figures[index].src"
          type="file"
          accept="image/*"
          @change="(fileDOM) => onChange(fileDOM, index)"
        />
        <div class="img-wrapper" v-if="figures[index].src">
          <i class="el-icon-delete" title="移除分图" @click="remove(index)" />
          <img :src="figures[index].src" />
          <div class="img-input">
            <label>{{ String.fromCharCode(97 + index) }})</label>
            <el-input size="small" v-model="figures[index].title"></el-input>
          </div>
        </div>
      </el-col>
    </el-row>
    <div class="btn-row">
      <el-button :disabled="figures.length === 4" icon="el-icon-plus" @click="addFigure"></el-button>
    </div>
    <span slot="footer">
      <el-button plain size="small" @click="handleClose">取消</el-button>
      <el-button type="primary" plain size="small" @click="confirm">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import tinymce from 'tinymce'
import dayjs from 'dayjs'
import { uploadFile } from '@/api'
import { Message } from 'element-ui'

export default {
  provide() {
    return {
      pageType: ''
    }
  },
  data() {
    return {
      figures: [{}, {}],
      dialogVisible: false
    }
  },
  methods: {
    addFigure() {
      this.figures.push({})
    },
    remove(index) {
      this.figures.splice(index, 1)
    },
    onChange(event, index) {
      const file = event.target.files[0]
      const reader = new FileReader()
      reader.onload = (evt) => this.$set(this.figures[index], 'src', evt.target.result)
      reader.readAsDataURL(file)
    },
    show() {
      this.dialogVisible = true
    },
    handleClose() {
      this.figures = [{}, {}]
      this.dialogVisible = false
    },
    async confirm() {
      if (this.figures.filter((i) => i.src).length < 2) {
        return Message.warning('请上传不少于2张图片')
      }
      if (this.figures.some((i) => i.title?.length > 16)) {
        return Message.warning('图标题请输入少于16个字符')
      }
      const canvas = document.createElement('canvas')
      canvas.width = 680
      // 550 = 10 + 240 + 5 + 20 + 240 + 5 + 20 + 10
      // 285 = 10 + 240 + 5 + 20 + 10
      canvas.height = this.figures.length > 2 ? 550 : 285
      const context = canvas.getContext('2d')
      context.font = '12pt 宋体'
      const promises = this.figures.map((figure, index) => {
        return new Promise((resolve) => {
          const img = new Image()
          img.src = figure.src
          img.crossOrigin = 'Anonymous'
          img.onload = () => {
            const ratio = img.width / (img.height * 1.3333)
            let width, height
            if (ratio > 1) {
              width = 320
              height = 240 / ratio
            } else {
              height = 240
              width = 320 * ratio
            }
            // context.drawImage(image, dx, dy, dWidth, dHeight)
            let dx = index % 2 === 0 ? 10 : 350
            if (this.figures.length === 3 && index === 2) dx = 180 // 当三个时的第三个
            let dy = index < 2 ? 10 : 275
            context.drawImage(img, dx + (320 - width) / 2, dy + (240 - height) / 2, width, height)

            // context.fillText(text, x, y, maxWidth)
            const text = String.fromCharCode(97 + index) + ') ' + (figure.title || '')
            dx = index % 2 === 0 ? 170 : 510
            if (this.figures.length === 3 && index === 2) dx = 340 // 当三个时的第三个
            dy = index < 2 ? 270 : 540
            context.textAlign = 'center'
            context.fillText(text, dx, dy)
            resolve()
          }
        })
      })

      await Promise.all(promises)
      canvas.toBlob(async (blob) => {
        const formData = new FormData()
        const filename = dayjs().format('YYYY-MM-DD HH:mm:ss') + '.png'
        formData.append('file', blob, filename)
        const { data: ossId } = await uploadFile(formData)
        tinymce.activeEditor.execCommand('mceUpdateImage', false, {
          caption: false,
          width: canvas.width,
          height: canvas.height,
          inline: false,
          isDecorative: false,
          src: window.location.origin + '/prod-api/editor/file/download/' + ossId
        })
      })

      this.handleClose()
      Message.success('插入成功')
    }
  }
}
</script>

<style scoped>
::v-deep .el-dialog__body {
  padding-bottom: 0;
}
.btn-row {
  text-align: center;
  padding-top: 10px;
}
.btn-row button {
  padding: 8px 60px;
}
.card {
  height: 200px;
  text-align: center;
}
.img-wrapper {
  position: relative;
}

.img-wrapper i {
  position: absolute;
  right: 20px;
  font-size: 18px;
  top: -10px;
  cursor: pointer;
  color: #f56c6c;
}
.img-wrapper img {
  width: 200px;
  height: 150px;
  object-fit: contain;
}
.img-input {
  display: flex;
  justify-content: center;
}
.img-input label {
  font-family: 黑体;
  align-self: center;
  font-size: 16px;
  margin-right: 6px;
}
.img-input ::v-deep .el-input {
  width: 80%;
}
</style>
